import { fill } from 'lodash-es';
import { pinia } from '@/store/index'
import { defineStore } from 'pinia'
import { useCommonStore } from './common';


export const useWebSocketStore = defineStore('websocket', {
  state: () => ({
    socketThis: null,
    onLine: false,
  }),
  actions: {
    onConnect (sn, callbackObj = {}) {
      if (!sn) sn = useCommonStore().snNo
      return new Promise(async (resolve, reject) => {

        if (!this.socketThis) {
          // 创建连接
          this.socketThis = await uni.connectSocket({
            url: `ws://39.101.198.55:7005/ecm/ws?sn=${sn}`,
            header: {
              'content-type': 'application/json'
            },
            // protocols: ['protocol1'],
            // method: 'GET',
            success: (res) => {
              console.log(res, '连接成功')

            },
            ...callbackObj
          });
          this.socketThis.onOpen((res) => {
            console.log(res, '打开成功')
            resolve(this.socketThis)
          })

          this.socketThis.onClose((res) => {
            console.log(res, '连接已关闭')
            reject(res)
          })

          this.socketThis.onError((res) => {
            console.log(res, '连接错误')
            this.onLine = false
            this.socketThis = null
            this.disconnectAndReconnect()
            reject(res)
          })

          this.socketThis.onMessage((res) => {
            console.log(res, '收到消息')

          })

        } else {
          resolve(this.socketThis)
        }
      })
    },
    onSend (data = '') {
      return new Promise((resolve, reject) => {
        if (!this.socketThis) {
          reject('socketThis is null')
        } else {
          console.log(data, '发送数据')
          this.socketThis.send({
            data,
            success: (res) => {
              console.log(res, '发送成功')
              resolve(res)
            },
            fill: (res) => {
              console.log(res, '发送失败')
              reject(res)
            }
          })
        }
      })
    },
    // 连接并发送登录信息
    async onConnectSend () {
      return new Promise(async (resolve, reject) => {
        try {
          if (!useCommonStore().token) return reject()
          await this.onConnect(useCommonStore().snNo)
          console.log('连接成功')
          const sendData = JSON.stringify({
            type: "device-message",
            content: JSON.stringify({
              snNo: useCommonStore().snNo,
              userId: useCommonStore().userId,
              appVersion: useCommonStore().appVersion,
              userName: useCommonStore().userInfo?.nickname,
            }),
          })
          await this.onSend(sendData)
          this.onLine = true
          resolve()
        } catch (error) {
          reject(error)
        }

      })
    },
    closeSocket (callbackObj = {}) {
      return new Promise((resolve, reject) => {
        if (!this.socketThis) {
          resolve()
        } else {
          this.socketThis.close({
            success: (res) => {
              console.log(res, '关闭成功')
              resolve(res)
            },
            fill: (res) => {
              console.log(res, '关闭失败')
              reject(res)
            },
            complete: (res) => {
              console.log(res, '关闭完成')
              this.socketThis = null
              this.onLine = false
            },
            ...callbackObj
          })
        }
      })
    },
    // 短线重连
    disconnectAndReconnect () {
      setTimeout(() => {
        console.log('重新连接')
        if (!this.onLine && useCommonStore().token) {
          this.onConnectSend();
        }
      }, 10 * 1000);
    }

  }

})

export const useWebSocketStoreWithOut = () => {
  return useWebSocketStore(pinia)
}
